//
//  SpriteLotus.m
//  FrogDrying
//
//  Created by Le Thanh Hai on 4/4/13.
//  Copyright 2013 __MyCompanyName__. All rights reserved.
//

#import "SpriteLotus.h"

@interface SpriteLotus()
-(BOOL)checkSpriteOutOfScreen:(CCSprite*)sp;
-(CCSprite*)getLastSprite;
@end


@implementation SpriteLotus
@synthesize lotus;

-(id)init
{
    if (self = [super init]) {
        lotus = [[NSMutableArray alloc] init];
        float offset = -130;
        for (int i = 0; i < 10; i++) {
            LotusAnimation *sp = [[LotusAnimation alloc] initWithFile:@"LotusLeaf.png"];
            sp.position = ccp(offset, 20);
            if (IS_IPHONE_5) {
                offset += 92;
            } else {
                offset += 82;
            }
            [self addChild:sp];
            [lotus addObject:sp];
        }
    }
    return self;
}

-(void)update:(ccTime)dt
{
    for(int i = 0; i < [lotus count]; i++) {
        CCSprite *sp = [lotus objectAtIndex:i];
        if ([self checkSpriteOutOfScreen:sp]) {
            float offset = arc4random() % 50 + 60;
            sp.position = ccpAdd([self getLastSprite].position, ccp(offset, 0));
            
            // move last object to first array
            id getSprite = [[[lotus objectAtIndex:i] retain] autorelease];
            [lotus removeObjectAtIndex:i];
            [lotus insertObject:getSprite atIndex:0];
            i = 0;
            return;
        }
        CGPoint point = sp.position;
        point.x -= 2;
        sp.position = point;
    }
}

#pragma mark - private function
-(BOOL)checkSpriteOutOfScreen:(CCSprite*)sp
{
    if (sp.position.x + 40 <= 0) {
        return TRUE;
    } else {
        return NO;
    }
}

-(CCSprite*)getLastSprite {
    CCSprite *temp = [lotus objectAtIndex:0];
    for (int i = 1; i < [lotus count]; i++) {
        CCSprite *sp = [lotus objectAtIndex:i];
        if (temp.position.x < sp.position.x) {
            temp = sp;
        }
    }
    return temp;
}
@end
